package cn.edu.henu.team.ui_test;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.bean._User;
import cn.edu.henu.team.bean.diagnosticLog;
import cn.edu.henu.team.table.diagLog;
import cn.edu.henu.team.table.diagLogUtils;
import cn.edu.henu.team.utils.CalendarDialog;
import cn.edu.henu.team.utils.VpSwipeRefreshLayout;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class DiagnoseLogActivity extends AppCompatActivity {
    private ImageView back;
    private VpSwipeRefreshLayout swipeRefreshLayout;
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private ScrollView scrollView;
    private int count = 0, num = 3, index = 1;
    //    @BindView(R.id.chart_riLi)
    private ImageView riLi;
    //    @BindView(R.id.time)
    private TextView time;
    private int now_year;
    private int now_month;
    int selectPos = -1, selectMonth = -1, selectYear = -1;

    //加载往期就医数据
    private ListView listView;
    private final List<Map<String, Object>> data = new ArrayList<>();
    private List<diagLog> datas;

    private SimpleAdapter simpleAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dlog);

        initView();
        initData();
        initClick();
    }

    protected void initView() {
        back = findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        swipeRefreshLayout = findViewById(R.id.refresh);
        listView = findViewById(R.id.listview);
        scrollView = findViewById(R.id.scroll);
        riLi = findViewById(R.id.chart_riLi);
        time = findViewById(R.id.time);

        Calendar calendar = Calendar.getInstance();
        now_year = calendar.get(Calendar.YEAR);
        now_month = calendar.get(Calendar.MONTH) + 1;
        selectYear = now_year;
        selectMonth = now_month;
        time.setText("当前日期: " + now_year + " 年 " + now_month + "月");

        if (scrollView != null) {
            scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                @Override
                public void onScrollChanged() {
                    if (swipeRefreshLayout != null) {
                        swipeRefreshLayout.setEnabled(scrollView.getScrollY() == 0);
                    }
                }
            });
        }
    }

    protected void initData() {
        datas = diagLogUtils.queryListByYearAndMonth(now_year, now_month);
        if (datas.size() < num) {
            for (diagLog t : datas) {
                Map<String, Object> temp = new LinkedHashMap<>();
                temp.put("objectId", t.getObjectId().toString());
                temp.put("time", t.getCreatedAt().toString());
                temp.put("pingYu", t.getContent().toString());
                temp.put("answer", t.getAnswer().toString());
                data.add(temp);
            }
        } else {
            for (int i = count; i < num; i++) {
                Map<String, Object> temp = new LinkedHashMap<>();
                temp.put("objectId", datas.get(i).getObjectId().toString());
                temp.put("time", datas.get(i).getCreatedAt().toString());
                temp.put("pingYu", datas.get(i).getContent().toString());
                temp.put("answer", datas.get(i).getAnswer().toString());
                data.add(temp);
            }
        }

        simpleAdapter = new SimpleAdapter(getApplicationContext(), data, R.layout.item_medical_record, new String[]{"objectId", "time", "pingYu", "answer"}, new int[]{R.id.objectId, R.id.time, R.id.pingYu, R.id.result});
        listView.setAdapter(simpleAdapter);
        setListViewHeightBasedOnChildren();
    }

    private void initClick() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //控件停留两秒
                            Thread.sleep(2000);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (datas.size() - index * num <= 0) {
                                        Toast.makeText(getApplicationContext(), "已经没有更多数据了", Toast.LENGTH_LONG).show();
                                        //停止
                                        swipeRefreshLayout.setRefreshing(false);
                                    } else {
                                        //更新数据
                                        data.clear();
                                        count += num;
                                        index++;
                                        if (datas.size() >= num * index) {
                                            for (int i = count; i < num * index; i++) {
                                                Map<String, Object> temp = new LinkedHashMap<>();
                                                temp.put("objectId", datas.get(i).getObjectId().toString());
                                                temp.put("time", datas.get(i).getCreatedAt().toString());
                                                temp.put("pingYu", datas.get(i).getContent().toString());
                                                temp.put("answer", datas.get(i).getAnswer().toString());
                                                data.add(temp);
                                            }
                                        } else {
                                            for (int i = count; i < datas.size(); i++) {
                                                Map<String, Object> temp = new LinkedHashMap<>();
                                                temp.put("objectId", datas.get(i).getObjectId().toString());
                                                temp.put("time", datas.get(i).getCreatedAt().toString());
                                                temp.put("pingYu", datas.get(i).getContent().toString());
                                                temp.put("answer", datas.get(i).getAnswer().toString());
                                                data.add(temp);
                                            }
                                        }

                                        simpleAdapter = new SimpleAdapter(getApplicationContext(), data, R.layout.item_medical_record, new String[]{"objectId", "time", "pingYu", "answer"}, new int[]{R.id.objectId, R.id.time, R.id.pingYu, R.id.result});
                                        listView.setAdapter(simpleAdapter);
                                        setListViewHeightBasedOnChildren();
                                        //停止
                                        swipeRefreshLayout.setRefreshing(false);
                                    }
                                }
                            });
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                // 点击获得该文章的objectId
                TextView t = v.findViewById(R.id.objectId);
                Intent it = new Intent(getApplicationContext(), FindSysLogActivity.class);
                it.putExtra("objectId", t.getText().toString());
                startActivity(it);
            }
        });

        riLi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCalendarDialog();
            }
        });
    }

    /* 显示日历对话框*/
    private void showCalendarDialog() {
        CalendarDialog dialog = new CalendarDialog(this, selectPos, selectMonth);
        dialog.show();
        dialog.setDialogSize();
        dialog.setOnRefreshListener(new CalendarDialog.OnRefreshListener() {
            @Override
            public void onRefresh(int selPos, int year, int month) {
                data.clear();
                datas.clear();
                count = 0;
                index = 1;
                datas = diagLogUtils.queryListByYearAndMonth(year, month);

                for (diagLog t : datas) {
                    Map<String, Object> temp = new LinkedHashMap<>();
                    temp.put("objectId", t.getObjectId().toString());
                    temp.put("time", t.getCreatedAt().toString());
                    temp.put("pingYu", t.getContent().toString());
                    temp.put("answer", t.getAnswer().toString());
                    data.add(temp);
                }
                simpleAdapter = new SimpleAdapter(getApplicationContext(), data, R.layout.item_medical_record, new String[]{"objectId", "time", "pingYu", "answer"}, new int[]{R.id.objectId, R.id.time, R.id.pingYu, R.id.result});
                listView.setAdapter(simpleAdapter);
                setListViewHeightBasedOnChildren();
            }
        });
    }

    //动态修改listview高度，使得listview能完全展开
    private void setListViewHeightBasedOnChildren() {
        if (listView == null) {
            return;
        }
        if (simpleAdapter == null) {
            return;
        }
        int totalHeight = 0;
        //Toast.makeText(getApplication(), Integer.toString(simpleAdapter.getCount()), Toast.LENGTH_SHORT).show();
        for (int i = 0; i < simpleAdapter.getCount(); i++) {
            View listItem = simpleAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (simpleAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}